using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class OfflineUnit : MonoBehaviour
{
	protected float MaxHealth = 100;
	protected float CurrentHealth = 100;
	protected float AttackPower = 20;
	public HealthBar OriginalBar;
	private HealthBar lifeBar;
	public float Speed;
	public float turnSpeed;
	private Vector3 Velocity = new Vector3();
	public LinkedList<Vector3> SeekTarget = new LinkedList<Vector3>();
	
	void Start()
	{
		this.gameObject.tag = "Unit";
		lifeBar = Instantiate(OriginalBar) as HealthBar;
		lifeBar.maxLife = MaxHealth;
		lifeBar.currentLife = CurrentHealth;
		lifeBar.setPos(Camera.main.WorldToScreenPoint(transform.position));
	}
	
	void Update ()
	{
		if(CurrentHealth <= 0)
			DeleteMe();
		Seek();
		UpdateLifeBar();
	}
	public virtual void DeleteMe(){}
	void Seek()
	{
		if(SeekTarget.Count > 0)
		{
			Vector3 gravity;
			gravity = SeekTarget.First.Value - transform.position;
			gravity.Normalize();
			gravity *= turnSpeed;
			Velocity += gravity;
			float slowfactor = 1/Vector3.Distance(transform.position, SeekTarget.First.Value);
			Velocity /= slowfactor;
			if(Velocity.magnitude > Speed)
			{
				Velocity.Normalize();
				Velocity *= Speed;
			}
			transform.position += Velocity;
			if(Vector3.Distance(transform.position, SeekTarget.First.Value) <= 5)
				SeekTarget.RemoveFirst();
		}
		else
			Velocity = Vector3.zero;
	}
	void UpdateLifeBar()
	{
		lifeBar.setPos(Camera.main.WorldToScreenPoint(transform.position));
		lifeBar.currentLife = CurrentHealth;
	}
	public void TakeDamage(float damage)
	{
		CurrentHealth -= damage;
		if(CurrentHealth <= 0)
			DeleteMe();
	}
	public void Heal(float amount)
	{
		if(CurrentHealth < MaxHealth)
			CurrentHealth += amount;
		if(CurrentHealth >= MaxHealth)
			CurrentHealth = MaxHealth;
	}
}
